package com.ruoyi.dictionaries.controller;

import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.dictionaries.domain.Regions;
import com.ruoyi.dictionaries.service.IRegionsService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 地区管理Controller
 *
 * @author gdslovehy
 * @date 2025-04-07
 */
@RestController
@RequestMapping("/dictionaries/regions")
public class RegionsController extends BaseController
{
    @Autowired
    private IRegionsService regionsService;

    /**
     * 查询地区管理列表
     */
   // @PreAuthorize("@ss.hasPermi('dictionaries:regions:list')")
    @GetMapping("/list")
    public AjaxResult list(Regions regions)
    {

        List<Regions> list = regionsService.selectRegionsList(regions);
        return success(list);
    }

    /**
     * 导出地区管理列表
     */
    @PreAuthorize("@ss.hasPermi('dictionaries:regions:export')")
    @Log(title = "地区管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Regions regions)
    {
        List<Regions> list = regionsService.selectRegionsList(regions);
        ExcelUtil<Regions> util = new ExcelUtil<Regions>(Regions.class);
        util.exportExcel(response, list, "地区管理数据");
        //asdasda
    }

    /**
     * 获取地区管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('dictionaries:regions:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(regionsService.selectRegionsById(id));
    }
    /**
     * 通过parent_id获取地区管理列表
     */
    @PreAuthorize("@ss.hasPermi('dictionaries:regions:query')")
    @GetMapping(value = "/listByParentId/{parentId}")
    public AjaxResult listByParentId(@PathVariable("parentId") Long parentId)
    {
        List<Regions> list = regionsService.selectRegionsListByParentId(parentId);
        return success(list);
    }
    /**
     * 新增地区管理
     */
    @PreAuthorize("@ss.hasPermi('dictionaries:regions:add')")
    @Log(title = "地区管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Regions regions)
    {
        /// 生成六位随机数编码作为新增时候的id并保证唯一性
        String id = String.valueOf((int) (Math.random() * 900000) + 100000);
        System.out.println(id);
        while (regionsService.selectRegionsById(id) != null) {
            id = String.valueOf((int) (Math.random() * 900000) + 100000);
            System.out.println(id);
        }
        regions.setId(id);
// 设置级别应为父节点的级别+1 如果父节点level为0则为0级否则为父节点的级别+1
        System.out.println(regions.getParentId());
        System.out.println(!String.valueOf(0).equals(regions.getParentId()));

        if (!"0".equals(regions.getParentId())) {
            Regions parent = regionsService.selectRegionsById(String.valueOf(regions.getParentId()));
            if (parent != null) {  // 添加空指针检查
                regions.setLevel(parent.getLevel() + 1);
            } else {
                // 处理父节点不存在的情况，可以设置默认值或抛出异常
                regions.setLevel(0); // 或者其他处理逻辑
            }
        } else {
            regions.setLevel(0);
        }
        System.out.println(regions.getLevel());

        return toAjax(regionsService.insertRegions(regions));
    }

    /**
     * 修改地区管理
     */
    @PreAuthorize("@ss.hasPermi('dictionaries:regions:edit')")
    @Log(title = "地区管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Regions regions)
    {
        return toAjax(regionsService.updateRegions(regions));
    }

    /**
     * 删除地区管理
     */
    @PreAuthorize("@ss.hasPermi('dictionaries:regions:remove')")
    @Log(title = "地区管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(regionsService.deleteRegionsByIds(ids));
    }
    /**
     * 从接口调用获取地区列表
     */
    @PreAuthorize("@ss.hasPermi('dictionaries:regions:query')")
    @GetMapping(value = "/updateRegions")
    public AjaxResult getupdateRegions(Regions regions)
    {
        regionsService.syncArea();
        List<Regions> list = regionsService.selectRegionsList(regions);
        return success(list);
    }
}
